package com.lUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class jdbcUtils {
    private static String driver=null ;
    private static String url =null;
    private static String username =null;
    private static String password =null;
    static {
            try{
                //读取配置文件，返回一个输入流
                InputStream inputStream =jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
                if (inputStream == null) {
                    throw new FileNotFoundException("配置文件未找到");
                }
                Properties properties= new Properties();
                // 加载这个流
                properties.load(inputStream);
                driver=properties.getProperty("driver");
                url=properties.getProperty("url");
                username=properties.getProperty("username");
                password=properties.getProperty("password");
                Class.forName(driver);

            }catch (Exception e){
                e.printStackTrace();
            }
    }

    public static Connection getConnection() throws SQLException {
        //返回了一个Connection 对象
        return   DriverManager.getConnection(url,username,password);
    }

    /**
     * 关闭 ResultSet，Statement，Connection 流
     * @param rs ResultSet 对象
     * @param stmt  Statement 对象
     * @param conn Connection 对象
     */

    public  static  void closeTheStream(ResultSet rs, Statement stmt, Connection conn){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
